﻿using Common.Infrastructure.Structs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

namespace Common.Infrastructure.Utils
{
    public static class LibEnumUtils
    {
        public static List<EnumInfo> GetLibEnumInfos(string searchPattern)
        {
            List<EnumInfo> result = new List<EnumInfo>();
            var files = System.IO.Directory.GetFiles(System.AppContext.BaseDirectory, searchPattern);
            if (files.Any())
            {
                foreach (var file in files)
                {
                    var assembly = Assembly.LoadFrom(file);
                    if (assembly != null)
                    {
                        foreach (var item in assembly.GetTypes())
                        {
                            if (item.IsEnum)
                            {
                                EnumInfo info = new EnumInfo();
                                info.EnumName = item.Name;
                                int i = 0;
                                bool isSort = false;
                                foreach (var x in Enum.GetValues(item))
                                {
                                    int tempIndex = i;
                                    EnumDetailInfo detailInfo = new EnumDetailInfo();
                                    detailInfo.Label = x.ToString();
                                    detailInfo.Value = (int)x;
                                    var fieldInfo = item.GetField(x.ToString());
                                    if (fieldInfo != null)
                                    {
                                        var enumSortIndexAttributes = (EnumSortIndexAttribute[])fieldInfo.GetCustomAttributes(typeof(EnumSortIndexAttribute), false);
                                        if (enumSortIndexAttributes.Any())
                                        {
                                            tempIndex = enumSortIndexAttributes[0].SortIndex;
                                            isSort = true;
                                        }
                                    }

                                    detailInfo.SortIndex = tempIndex;
                                    i++;
                                    info.Options.Add(detailInfo);
                                }

                                if (isSort)
                                {
                                    info.Options = info.Options.OrderBy(t => t.SortIndex).ToList();
                                }

                                result.Add(info);
                            }
                        }
                    }
                }
            }

            return result;
        }
    }
}
